import axios from "axios";
import { endpoint, baseEndpoint } from "../config/constants";
const formatDate = (day) => {
  const dd = ("0" + day.getDate()).slice(-2);
  const mm = ("0" + (day.getMonth() + 1)).slice(-2);
  const yy = day.getFullYear();
  return `${yy}${mm}${dd}`;
};

/*-----------------------Axios Wrapper-------------------*/
/**
 * @param { Promise } promise
 * @param { Object } improved - If you need to enhance the error.
 * @return { Promise }
 */
export function to(promise,improved) {
  return promise
    .then((data) => [null, data])
    .catch((err) => {
      if (improved) {
        Object.assign(err, improved);
        // console.log(improved);s
      }
      return [err, null]; // which is same as [err, undefined];
    });
}

export const requestPackByCode = async (code) => {
  const method = "packing";
  const query = `{
    packing(code:"${code}") {
      status
      type
      product_items {
        code
        schedule_id
        metadata {
          batch_num
          product {
            id
            name
            specs
            outer_packing_units
            license_num
            manufacture
          }
        }
      }
      addr{
        id
        receiver
        phone_number
        province
        city
        county
        address
      }
    }
  }`;
  return await sendRequestQuery(query, method);
};

export const requestProductItemByCode = async (code) => {
  const method = "product_item";
  const query = `{
    product_item(code:"${code}") {
      code
      metadata {
        batch_num
        product  {
          name
          specs
          manufacture
          license_num
        }
      }
      packing {
        code
        addr{
          id
          receiver
          phone_number
          province
          city
          county
          address
        }
      }
     }
    }`;
  return await sendRequestQuery(query, method);
};

export const requestNewParents = async (n) => {
  // const [err, res] = await to(
  //   axios.get(`${baseEndpoint}/generate-parent/${n}`)
  // );
  // if (err != null || res == null) {
  //   return null;
  // }
  // return res.data;

  var element = document.createElement("a");
  element.setAttribute("href", `${baseEndpoint}/generate-parent/${n}`);
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
};

export const requestNewChildren = async (n) => {
  // const [err, res] = await to(
  //   axios.get(`${baseEndpoint}/generate-child/${n}`, {
  //     timeout: 10 * 60 * 1000,
  //   })
  // );
  // if (err != null || res == null) {
  //   return null;
  // }
  // return res.data;

  var element = document.createElement("a");
  element.setAttribute("href", `${baseEndpoint}/generate-child/${n}`);
  document.body.appendChild(element);
  element.click();
  document.body.removeChild(element);
};

export const requestSchedule = async (
  status,
  page,
  limit
) => {
  const method = "schedule_page";
  let queryPayload = `query {
    schedule_page(status:${status}, page:${page}, limit:${limit}){
      total
      results {
        id
        date
        product{
          name
          specs
          outer_packing_units
        }
        batch_num
        amount
        work_progress {
          related {
            sum_of_packed_items
            sum_of_packs
            sum_of_cus
          }
          storage1{
            sum_of_packed_items
            sum_of_packs
            sum_of_cus
          }
          storage2{
            sum_of_packed_items
            sum_of_packs
            sum_of_cus
          }
          delivered{
            sum_of_packed_items
            sum_of_packs
            sum_of_cus
          }
          sum_of_unpacked_items
          sum_of_to_deliver_items
          sum_of_related_items
        }
      }
    }
  }`;

  return await sendRequestQuery(queryPayload, method);
};

export const requestAddressData = async () => {
  let queryPayload = `query {
    addresses {
      id
      receiver
      phone_number
      province
      city
      county
      address
    }
  }`;
  const [err, res] = await to(
    axios.post(endpoint, {
      query: queryPayload,
    })
  );
  if (err) return null;
  else return res.data.data.addresses;
};

export const requestDeliveryPlan = async (page, limit) => {
  const method = "delivery_plan_page";
  let queryPayload = `query{
    ${method}(status:NORMAL, page:${page}, limit:${limit}){
      total
      results{
          id
          task{
            id
            batch_num
            product{
              name
              specs
            }
            work_progress{
              delivered{
                sum_of_packs
              }
            }
          }
          addr{
            id
            receiver
            phone_number
            province
            city
            county
            address
          }
          date
          amount
        }
      }
  }`;
  console.log(queryPayload);
  return await sendRequestQuery(queryPayload, method);
};

const sendRequestQuery = async (query, method) => {
  const [err, res] = await to(
    axios.post(endpoint, {
      query: query,
    })
  );
  if (err) return null;
  else return res.data.data[method];
};

export const requestProductData = async () => {
  let queryPayload = `query {
    products {
      id
      name
      specs
      outer_packing_units
      outer_packing_desc
      license_num
    }
  }`;
  const [err, res] = await to(
    axios.post(endpoint, {
      query: queryPayload,
    })
  );

  if (err) return null;
  else return res.data.data.products;
};

export const callAddAddress = async (
  receiver,
  phone,
  province,
  city,
  county,
  addr
) => {
  let queryPayload = `
      mutation {
        addAddress(addr:{
          receiver: "${receiver}"
          phone_number:"${phone}"
          province:"${province}"
          city:"${city}"
          county:"${county}"
          address:"${addr}"
        }) {
          id
        }
      }
    `;
  const [err, res] = await to(
    axios.post(endpoint, {
      query: queryPayload,
    })
  );
  if (err || !res.data.data["addAddress"]) {
    return false;
  }
  return true;
};

export const callAddProduct = async (
  productName,
  specs,
  outer_packing_units,
  outer_packing_desc,
  license_num
) => {
  let addQuery = `mutation {
    createProduct(
      product: {
        name: "${productName}"
        specs: "${specs}"
        manufacture: "飘安生产管理系统"
        outer_packing_units: ${outer_packing_units}
        outer_packing_desc: "${outer_packing_desc}"
        license_num: "${license_num}"
      }
    ) {
      id
    }
  }`;
  let [err, res] = await to(
    axios.post(endpoint, {
      query: addQuery,
    })
  );
  if (err || !res.data.data["createProduct"].id) {
    return false;
  }
  return true;
};

export const callAddTask = async (
  selectedDate,
  productId,
  batchNum,
  amount
) => {
  const dd = formatDate(selectedDate);
  let queryPayload = `mutation {
    addTask(task: { date: "${dd}", product_id: ${productId}, batch_num: "${batchNum}", amount: ${amount} })
  }`;
  console.log(queryPayload);
  let [, res] = await to(
    axios.post(endpoint, {
      query: queryPayload,
    })
  );
  if (res.data.data.addTask === "SUCCEED") {
    return true;
  } else {
    return false;
  }
};

export const callEditProduct = async (
  id,
  name,
  specs,
  units,
  desc,
  license
) => {
  let queryPayload = `
    mutation {
         updateProduct(
           product: {
             id: ${id}
             name: "${name}"
             specs: "${specs}"
             manufacture: "飘安生产管理系统"
             outer_packing_units: ${units}
             outer_packing_desc: "${desc}"
             license_num: "${license}"
           }
         )
       }
    `;
  return await sendUpdateQuery(queryPayload, "updateProduct");
};

export const callAddDeliveryPlan = async (
  selectedDate,
  taskId,
  addrId,
  amount
) => {
  const dd = formatDate(selectedDate);
  let queryPayload = `mutation {
    addDeliveryPlan(
      plan: { date: "${dd}", task_id: ${taskId}, addr_id: ${addrId}, amount: ${amount} }
    )
  }`;
  console.log(queryPayload);
  return await sendUpdateQuery(queryPayload, "addDeliveryPlan");
};

const sendUpdateQuery = async (query, method) => {
  let [err, res] = await to(
    axios.post(endpoint, {
      query: query,
    })
  );
  if (res.data.data[method] === "SUCCEED") {
    return true;
  } else {
    console.log(err);
    return false;
  }
};

export const callDeleteDeliveryPlan = (id, onsuccess, onerror) => {
  callDeleteQuery("deleteDeliveryPlan", id, onsuccess, onerror);
};

export const callDeleteProduct = (id, onsuccess, onerror) => {
  callDeleteQuery("deleteProduct", id, onsuccess, onerror);
};

export const callDeleteAddr = (id, onsuccess, onerror) => {
  callDeleteQuery("deleteAddr", id, onsuccess, onerror);
};

const callDeleteQuery = (query, id, onsuccess, onerror) => {
  let delQuery = `mutation {
    ${query} (id: ${id})
  }`;
  axios
    .post(endpoint, {
      query: delQuery,
    })
    .then((res) => {
      if (res.data.data[query] === "SUCCEED") {
        onsuccess();
      } else alert("删除失败！请检查网络设置！");
    })
    .catch((err) => {
      console.log(err);
      if (onerror) onerror(err);
      else {
        alert("删除失败！请检查网络设置！");
      }
    });
};

// const request
